from wormbane.engine.actions.hit import action_hit

import random

class Ai(object):
    def update(self, game):
        for monster in game.level.monsters:
            if monster is not game.hero:
                self._update_monster(monster, game)

    def _update_monster(self, monster, game):
        offset = game.hero.pos - monster.pos
        if abs(offset.x) <= 1 and abs(offset.y) <= 1:
            action_hit(monster, game.hero, game)
        elif monster.pos in game.level.field_of_view:
            def distance(thing):
                return abs(game.hero.pos - thing.pos)
            exits = sorted(monster.cell_env.exits, key = distance)
            if exits and distance(exits[0]) <= distance(monster):
                monster.move_to(exits[0])
        else:
            cell = random.choice([None] + list(monster.cell_env.exits))
            if cell:
                monster.move_to(cell)
